'use strict'

const http = require('http');
const fs = require('fs');
const {
  promisify
} = require('util');
const path = require('path');
const socketIo = require('socket.io');
const mime = require('mime');
const opn = require('opn');
const names = require('./lib/getName');
const titles = require('./lib/getTitle.js');

(async function () {
  const readFile = promisify(fs.readFile); //读取文件
  const nameData = await names();
  const nameList = nameData.toString().split(',');
  const titleData = await titles();
  const titleList = titleData.toString().split(',');
  let userList = [];

  //服务器处理函数
  function handler(req, res) {
    let url = req.url; //当前路径
    let filePath = '' //记录文件路径，用于发送文件

    if (url === '/') {
      filePath = path.join(__dirname, '../client/index.html');
    } else if (url === '/favicon.ico') { //网站图标
      return;
    } else {
      filePath = path.join(__dirname, '../client' + url);
    }
    res.writeHead(200, {
      'Content-type': mime.lookup(filePath) //判断文件类型
    });

    readFile(filePath).then((data) => {
      res.end(data); //发送读取到的文件
    }).catch((err) => {
      console.log(err); //输出错误
    });
  }


  const app = http.createServer(handler).listen(3000);

  //socket通信转发
  const io = socketIo(app);

  io.on('connection', (socket) => {
    if (userList.length < 3) {
      let name = nameList[Math.floor(Math.random() * nameList.length)];
      userList.push({
        name: name,
        sid: socket.id
      });

      socket.join('draw', function () {
        io.sockets.to('draw').emit('name', { //发送用户列表
          userList: userList
        });
        socket.emit('myname', name); //自己名字
      });

      socket.on('say', (data) => {
        socket.broadcast.to('draw').emit('listen', data);
      })

      socket.on('start', (data) => {
        socket.broadcast.to('draw').emit('start', data);
      })

      socket.on('move', (data) => {
        socket.broadcast.to('draw').emit('move', data);
      })

      socket.on('style', (data) => {
        socket.broadcast.to('draw').emit('style', data);
      });

      socket.on('clear', () => {
        socket.broadcast.to('draw').emit('clear');
      });

      socket.on('disconnect', () => {
        delBySid(socket.id);
      })
    } else {
      socket.emit('sys', '房间已满人');
    }

  });

  function delBySid(sid) {
    var list = [];
    for (var i of userList) {
      if (i.sid !== sid) {
        list.push(i);
      }
    }
    return (userList = list);
  }
  console.log('用浏览器打开 localhost:3000');
})();